// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate

// 云函数入口函数
exports.main = async (event, context) => {

  switch (event.action) {
    case 'up': return  up(event)
    case 'down':return down(event)
    case 'getTempFile': return getTempFile(event)
    case 'sendResume' : return sendResume(event)
    case 'sendWorks' : return sendWorks(event)
    default: return Promise.reject("unknown action")
  }
}
async function up(event){
    return 1
}

async function down(event){
  //const fileID = "cloud://cloud1-6gvg8052f9670276.636c-cloud1-6gvg8052f9670276-1305457435/05b34594-d90d-4773-ab94-91bebc2c5f3b.docx"
  const fileID = event.data.fileID 

  
  const res = await cloud.downloadFile({
    fileID: fileID,
  })
  return res
}
async function getTempFile(event){
  const fileList = event.data.fileList 
  const result = await cloud.getTempFileURL({
    fileList: fileList,
  })
  return result.fileList
} 

async function sendResume(event){
  var openid = event.data.targetID //这是目标的id
  var file = event.data.file      //这是需要穿的文件，里面有name,file的路径叫做file
  var Myopenid =event.data.Myopenid // 这是我的openid
  var params = {file,Myopenid}
  console.log(openid)
 console.log(params)
  return new Promise((reslove,reject)=>{
   db.collection('user').where({
     _openid:openid
   }).update({
      data:{
        yourResume:_.push(params)
      },
    }).then(res=>{
      reslove({message:"发送简历成功",coded:200,data:res})
    }).catch(err=>{
      reject({message:"发送简历失败",code:404,data:err})
    })
  })
  
}
async function sendWorks(event){
  var openid = event.data.targetID //这是目标的id
  var file = event.data.file      //这是需要穿的文件，里面有name,file的路径叫做file
  var Myopenid =event.data.Myopenid // 这是我的openid
  var params = {file,Myopenid}
  
  return new Promise((reslove,reject)=>{
    db.collection('user').where({
      _openid:openid
    }).update({
      data:{
        yourWorks:_.push(params)
      }
    }).then(res=>{
      reslove({message:"发送作品成功",coded:200,data:res})
    }).catch(err=>{
      reject({message:"发送简历失败",code:404,data:err})
    })
  })
  
}